from locust import HttpUser, task, between
import urllib.parse
import random
import string

class UserRegistrationTest(HttpUser):
    wait_time = between(1, 3)  # 定义每个用户的等待时间范围

    def generate_random_payload(self):
        payload = {
            'userName': ''.join(random.choices(string.ascii_lowercase, k=8)),
            'email': ''.join(random.choices(string.ascii_lowercase, k=8)) + '@example.com',
            'passWord': ''.join(random.choices(string.ascii_lowercase + string.digits, k=8)),
            'trueName': ''.join(random.choices(string.ascii_lowercase, k=8)),
            'phone': ''.join(random.choices(string.digits, k=11)),
            'userType': 'student',
            'school': 'testschool',
            'schoolId': '123456',
            'yard': 'testyard',
            'major': 'testmajor',
            'inSchoolTime': '2020-01-01',
            'tSchool': 'testtschool',
            'teachId': '123456',
            'workId': '123456'
        }
        return payload
    
    @task
    def register_user(self):
        headers = {'Content-Type': 'application/x-www-form-urlencoded'}
        payload = self.generate_random_payload()
        data = urllib.parse.urlencode(payload)
        response = self.client.post('/auth/register', data=data, headers=headers)
        if response.status_code == 200:
            print('User registered successfully!')
        else:
            print('User registration failed.')

    def on_start(self):
        # 在启动测试之前执行的操作，例如登录等
        pass
